package com.example.nonggo.view.act;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.api.BaseApi;
import com.example.nonggo.api.MDataObserver;
import com.example.nonggo.bean.BdsoundDTO;
import com.example.nonggo.bean.BdsoundVO;
import com.example.nonggo.bean.SubmitQuestionBody;
import com.example.nonggo.utils.CustomToastUtils;
import com.example.nonggo.utils.FileUtils;
import com.example.nonggo.widget.WaveformView;
import com.tencent.mmkv.MMKV;

import java.io.File;

/**
 * 专家问答
 */
public class ExpertQaActivity extends AppCompatActivity {
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private volatile MediaRecorder mRecorder;
    private static final String TAG = ExpertQaActivity.class.getName();
    private boolean isRecording = false;
    private final String[] permissions = {Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE,};


    private File audioFile;

    private Handler handler;
    private Runnable updateWaveformRunnable;

    WaveformView waveformView;
    private long startRecordTime = 0;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        getWindow().setNavigationBarColor(Color.TRANSPARENT);
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(visibility -> {
            if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                // 若状态栏显示，再次隐藏
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                );
            }
        });
        setContentView(R.layout.activity_expert_qa);
        findViewById(R.id.back_button).setOnClickListener(v -> finish());
        findViewById(R.id.btnSubmit).setOnClickListener(v -> submitQuestion());

        findViewById(R.id.success_mask_layout).setOnClickListener(v -> {
            v.setVisibility(View.GONE);
        });
        waveformView = findViewById(R.id.waveformView);
        // 初始化 Handler
        handler = new MyHandler();
        // 初始化 Runnable
        updateWaveformRunnable = new Runnable() {
            @Override
            public void run() {
                // 更新波形
                updateWaveform();
                handler.postDelayed(this, 250); // 每 250 毫秒更新一次
            }
        };
        // 获取输入框
//        etInputQuestion = findViewById(R.id.et_input_question);
        // 设置btnMic的点击事件
        ImageView btnMic = findViewById(R.id.btnMic);
        btnMic.setOnClickListener(v -> {
            if (ActivityCompat.checkSelfPermission(v.getContext(), Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(v.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                startRecording();
            } else {
                ActivityCompat.requestPermissions(this, permissions, REQUEST_RECORD_AUDIO_PERMISSION);
            }
        });

        EditText etInputQuestion = findViewById(R.id.et_input_question);
        etInputQuestion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                    hideStatusBar();
                }
            }
        });

    }

    private void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private void hideStatusBar() {
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
    }

    private void submitQuestion() {
        EditText etInputQuestion = findViewById(R.id.et_input_question);
        if (etInputQuestion.getText().toString().isEmpty()) {
            return;
        }
        String token = MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN, "0");
        String mobile = MMKV.defaultMMKV().getString(Constants.MOBILE, "0");
        RxHttpUtils.createApi(BaseApi.class)
                .submitQuestion(token,new SubmitQuestionBody(etInputQuestion.getText().toString(),mobile ).toRequestBody())
                .compose(Transformer.switchSchedulers())
                .subscribe(new MDataObserver<>() {
                    @Override
                    protected void onSuccess(Object data) {
                        View view = findViewById(R.id.success_mask_layout);
                        view.setVisibility(View.VISIBLE);
                        view.setOnClickListener(v -> {v.setVisibility(View.GONE);});
                        etInputQuestion.setText("");
                    }
                });
    }

    private static class MyHandler extends Handler {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予
                startRecording();
            } else {
                // 检查用户是否勾选了 "不再询问"
                if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                    // 显示提示对话框或执行其他操作
                }
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void startRecording() {
        View micMaskLayout = findViewById(R.id.mic_mask_layout);
        waveformView.setOnFinishListener(this::stopRecordingAndTranscribe);
        micMaskLayout.setOnClickListener(v -> {
            stopRecordingAndTranscribe();
        });
        startRecordTime = System.currentTimeMillis();
        audioFile = new File(this.getFilesDir() + "/" + "voice_" + System.currentTimeMillis() + ".wav");
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            if (mRecorder != null) {
                mRecorder.reset();
            } else {
                mRecorder = new MediaRecorder();
            }
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(16000);

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mRecorder.setOutputFile(audioFile);
                }
                mRecorder.prepare();
                mRecorder.start();
            } catch (Exception e) {
                mRecorder.release();
                mRecorder = null;
                toast("录音失败");
                return ;
            }
            isRecording = true;
            micMaskLayout.setVisibility(View.VISIBLE);
            handler.post(updateWaveformRunnable); // 启动 Runnable
        } catch (Exception e) {
            Log.d(TAG, "startRecording: ");
        }
    }
    private void toast(String content) {
        Toast.makeText(this, content, Toast.LENGTH_SHORT).show();
    }
    private void stopRecordingAndTranscribe() {
        View micMaskLayout = findViewById(R.id.mic_mask_layout);
        if (micMaskLayout.getVisibility() != View.GONE) {
            micMaskLayout.setVisibility(View.GONE);
        }
        // 录音小于2秒则不进行识别
        if (System.currentTimeMillis() - startRecordTime < 2000) {
            CustomToastUtils.showCustomToast("录音时间太短");
            return;
        }
        if (mRecorder != null) {
            isRecording = false;
            mRecorder.stop();//停止时没有prepare，就会报stop failed
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            handler.removeCallbacks(updateWaveformRunnable);

            // 这里可以调用语音转文字的API
            transcribeAudio(audioFile.getAbsolutePath());
        }
    }

    private void transcribeAudio(String absolutePath) {

        Log.e("ExpertQaActivity", "transcribeAudio: " + absolutePath);
        String s = FileUtils.fileToBase64(absolutePath);
        File convertedFile = new File(absolutePath);
        String token = MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN, "0");
        RxHttpUtils.createApi(BaseApi.class)
                .bdsound(token, new BdsoundDTO(s, convertedFile.length()).toRequestBody())
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<>() {
                    @Override
                    protected void onSuccess(BdsoundVO data) {
                        if (data.getResult() == null|| data.getResult().length == 0) {
                            CustomToastUtils.showCustomToast("识别失败");
                            return;
                        }
                        Log.e(TAG, "onSuccess: " + data.getResult()[0]);
                        EditText view = findViewById(R.id.et_input_question);
                        view.getText().append(data.getResult()[0]);
                    }
                    @Override
                    public void doOnCompleted() {
                        super.doOnCompleted();
                        try {
                            // 根据路径删除文件
                            if (convertedFile.exists()) {
                                convertedFile.delete();
                            }
                        } catch (Exception ignore) {

                        }
                    }
                });
    }

    private void updateWaveform() {
        if (!isRecording) return;
        int maxAmplitude = mRecorder.getMaxAmplitude();
        int db = maxAmplitude / 35;
          Log.i(TAG, "分贝:" + db);
        db = Math.min(200, db);
        if (waveformView == null) {
            waveformView = findViewById(R.id.waveformView);
        }
        // 更新波形视图
        waveformView.addVoiceSize(db);
    }
    // 添加窗口焦点变化监听
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRecorder != null) {
            mRecorder.release();
            mRecorder = null;
        }
        waveformView.onDestroy();
        // 移除 Runnable
        if (handler != null) {
            handler.removeCallbacks(updateWaveformRunnable);
            handler = null;
        }
    }
}